new Vue({
	el: '#mainBody',
	data: function() {
		var validateSuppliersName = function (rule, value, callback) {
	        if (value!=null&&value.trim() === '') {
	          callback(new Error('请输入正确的供应商名称'));
	        }else{
	        	callback();
	        }
	      };
	      var validatePass = function(rule, value, callback){
		        if (value!=null&&value === 'null') {
		          callback(new Error('输入非法值,请修改'));
		        }else{
		        	callback();
		        }
		  };
		  var validateNumber = function(rule, value, callback) {
		        if (value!=null&&value.trim() !='') {
		        	if (!/^[0-9]+(.[0-9]{1,2})?$/.test(value)) {
			            callback(new Error('精确小数点后两位'));
			          }else{
				        	callback();
				        }
		        }else{
		        	callback();
		        }
		  };
		  var validateEmail = function(rule, value, callback){
		        if (value!=null&&value.trim() !='') {
		        	if (!/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test(value)) {
			            callback(new Error('请输入正确的邮箱'));
			          }else{
				        	callback();
				        }
		        }else{
		        	callback();
		        }
		  };
	    var validateSuppliersContacts = function(rule, value, callback){
		        if (value!=null&&value.trim() === '') {
			          callback(new Error('请输入正确的联系人'));
			        }else{
			        	callback();
			        } 
		};
		var validateSuppliersPhone = function(rule, value, callback){
			if (value!=null&&value.trim() !='') {
		        if (!/(^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$)|(^((\d3)|(\d{3}\-))?(1[0-9]\d{9})$)/.test(value)) {
			          callback(new Error('请输入正确的联系电话'));
		        }else{
		        	callback();
		        }
		  }else{
			  callback();
	        }
		};
		return {
			branchs: [ //机构
			],
			currentpage : 1,// 当前页数
			pageBean : [// 分页参数列表
			],
			viewTitle: '', //查看修改title
			showDialog: false,
			isSearch: false,
			suppliersCategory: [ //供应商类别
			],
			suppliers: [ //供应商
			],
	/*		suppliersNames: [ //供应商名称
			 {"value":"中科软"},
			 {"value":"中科软科技"}
			 			],*/
			suppliersServices: [ //服务项目
			],
			searchForm: { //查询条件
				suppliersName: '', //供应商名称
				suppliersCategory: '', //供应商类别
				suppliersService: '' //服务项目
			},
			suppliersForm: { //查看修改的数据
				suppliersName: '',
				suppliersCategory: '',
				suppliersContacts: '',
				suppliersPhone: '',
				suppliersEmail: '',
				suppliersOrgan: '',
				suppliersNodes: '',
				suppliersAddress: '',
				suppliersLicense: '',
				suppliersPermit: '',
				otherAttachment: '',
				suppliersServiceItems: [
					{
						suppliersServiceName: '',
						suppliersServicePrice: '',
						suppliersServiceContacts: '',
						suppliersServicePhone: '',
						suppliersServiceEmail: ''
					}
				]
			},
			showRules: { //form 验证
				suppliersOrgan: [
								{
									required: true,
									message: '请选择所属机构',
									trigger: 'blur'
								}
				                 ],
				suppliersName: [
								{
									required: true,
									message: '请输入正确的供应商名称',
									trigger: 'blur'
								},
								{ validator: validateSuppliersName, trigger: 'blur' },
								{ validator: validatePass, trigger: 'blur' }
								
								],
				suppliersCategory: [
									{
										required: true,
										message: '请选择正确的供应商类别',
										trigger: 'change'
									}
									],
				suppliersContacts: [
									{
										required: true,
										message: '请输入正确的联系人',
										trigger: 'blur'
									},
									{ validator: validateSuppliersContacts, trigger: 'blur' },
									{ validator: validatePass, trigger: 'blur' }
									],
				suppliersPhone: [
								{ validator: validateSuppliersPhone, trigger: 'blur' },
								],
				suppliersEmail: [
				                 { validator: validateEmail, trigger: 'blur' }
				                 ],
				suppliersNodes: [
								{ validator: validatePass, trigger: 'blur' }
								],
				suppliersAddress: [
								{ validator: validatePass, trigger: 'blur' }
								],
				suppliersServiceName: [
									{
										required: true,
										message: '请选择正确的服务项目',
										trigger: 'blur'
									}
									],
			   suppliersServicePrice: [
			                           { validator: validateNumber, trigger: 'blur' }
									],
			   suppliersServiceContacts: [
			                              { validator: validatePass, trigger: 'blur' }
									   ],
			   suppliersServicePhone: [
			                           { validator: validateSuppliersPhone, trigger: 'blur' },
									  ],
			  suppliersServiceEmail: [
			                           { validator: validateEmail, trigger: 'blur' },
									 ]
			},
			isDisabled: false, //form isDisabled
			isEdit: true, //新建供应商服务
			suppliersList: [ //供应商查询结果列表
			]
		}
	},
	created : function() {
		this.findSuppliers();
		this.loadOption();
	},
	methods: {
		handlePreview: function () {
            // 点击已上传的文件链接时的钩子，可以通过file.response拿到服务端返回数据
        },
        handleRemove_1: function (file, fileList) {
            // 文件列表移除文件时的钩子
        	this.suppliersForm.suppliersLicense=fileList;
        },
        handleRemove_2: function (file, fileList) {
            // 文件列表移除文件时的钩子
        	this.suppliersForm.suppliersPermit=fileList;
        },
        handleRemove_3: function (file, fileList) {
            // 文件列表移除文件时的钩子
        	this.suppliersForm.otherAttachment=fileList;
        },
        beforeRemove: function (file, fileList) {
            // 删除文件之前的钩子，参数为上传的文件和文件列表，若返回false或者返回Promise且被reject，则停止上传。
        	return this.$confirm('确定移除' + file.name)
        },
     // 上传成功后的回调
        uploadSuccess_1: function(response, file, fileList) {
        	var att = response.data;
        	var index = fileList.indexOf(file)
            if (index !== -1) {
            	fileList[index]=att;
            }
        	this.suppliersForm.suppliersLicense=fileList;
    
          console.log('上传文件', response)
        },
        uploadSuccess_2: function(response, file, fileList) {
        	var att = response.data;
        	var index = fileList.indexOf(file)
            if (index !== -1) {
            	fileList[index]=att;
            }
        	this.suppliersForm.suppliersPermit=fileList;
    
          console.log('上传文件', response)
        },
        uploadSuccess_3: function(response, file, fileList) {
        	var att = response.data;
        	var index = fileList.indexOf(file)
            if (index !== -1) {
            	fileList[index]=att;
            }
        	this.suppliersForm.otherAttachment=fileList;
    
          console.log('上传文件', response)
        },
        // 上传错误
        uploadError: function(response, file, fileList) {
          console.log('上传失败，请重试！')
        },

        handleExceed: function (file, fileList) {
            // 文件超出个数限制时的钩子
            this.$message.warning('当前限制选择3个文件，本次选择了' + file.length + '个文件，共选择了' + Number(file.length +fileList.length) + '个文件')
        },
		/**
		 * 下一页上一页按钮
		 */
		handleCurrentChange : function(val) {
			this.currentpage = val;
			this.findSuppliers();
		},
		search : function() {
			this.currentpage = 1;
			this.isSearch=true;
			this.findSuppliers();
		},
		findSuppliers : function() {
			var _this = this;
			var data = "{}";
			if(_this.isSearch){
				data = JSON.stringify(_this.searchForm);
			}
			$.ajax({
				url : '/suppliers/findSuppliers',
				type : 'post',
				data : {
					"data" : data,
					"page" : _this.currentpage
				},
				dataType : 'json',
				success : function(res) {
					_this.exhibition(res);
				},
				error : function(err) {
					if(err.status == 403){
                        errorMessage(_this.$message, "没有权限，请先申请该权限！");
                        return;
                    }
					if(err.responseJSON.message=="session clean"){
                        errorMessage(_this.$message, '登陆已失效重新登陆!');
                        toLogin();
                        return;
                    }
					errorMessage(_this.$message, '获取供应商列表出错！')
				}
			})
		},
		addSuppliers: function() { //新建供应商
			this.viewTitle = '新建供应商'
			this.showDialog = true
			this.suppliersForm = {}
			this.$set(this.suppliersForm, 'suppliersServiceItems', [{suppliersServiceName:'',suppliersServicePrice:'',suppliersServiceContacts:'',suppliersServicePhone:'',suppliersServiceEmail:''}])
			this.isDisabled = false
			this.isEdit = true
		},
		closeDialog: function(formName) { //关闭清除校验结果
			this.$refs[formName].clearValidate()
		},
		resetSearchForm: function(formName) { //清空搜索条件
			this.$refs[formName].resetFields()
			this.isSearch=false;
			this.findSuppliers();
		},
		viewItem: function(index) { //查看
			this.showDialog = true
			this.suppliersForm = this.suppliersList[index]
			this.viewTitle = '查看供应商'
			this.isDisabled = true
			this.isEdit = false
		},
		changeItem: function(index) { //修改
			this.showDialog = true
			this.selectedForm = index
			this.suppliersForm = JSON.parse(JSON.stringify(this.suppliersList[index]))
			this.viewTitle = '修改供应商'
			this.isDisabled = false
			this.isEdit = true
		},
		deleteItem: function(index) { //删除
			var _this = this
			var id = this.suppliersList[index].id;
			this.$confirm('确认要删除该条记录？', '删除提示', {
	                confirmButtonText: '确定',
	                cancelButtonText: '取消',
	                type: 'warning'
	            }).then(function () {
					$.ajax({
		                url: '/suppliers/delSuppliers',
		                data: {"id":id},
		                type: 'post',
		                dataType: 'json',
		                success: function (res) {
		                	successMessage(_this.$message, '删除成功');
		                	_this.findSuppliers();
		                	_this.loadOption();
		                },
		                error: function (err) {
		                	if(err.status == 403){
		                        errorMessage(_this.$message, "没有权限，请先申请该权限！");
		                        return;
		                    }
		                	if(err.responseJSON.message=="session clean"){
		                        errorMessage(_this.$message, '登陆已失效重新登陆!');
		                        toLogin();
		                        return;
		                    }
		                	errorMessage(_this.$message, '删除失败，联系管理员!');
		                }
		            });
	            });
		},
		saveForm: function(formName) { //保存
			var _this = this
			this.$refs[formName].validate(function(valid) {
				if (valid) {
		        	$.ajax({
		                url: '/suppliers/saveOrupdateSuppliers',
		                data: {"data":JSON.stringify(_this.suppliersForm)},
		                type: 'post',
		                dataType: 'json',
		                success: function (res) {
		                	var update = '';
		                    _this.$alert('','保存成功', {
		                        confirmButtonText: '确定',
		                        type:'success',
		                        center:'true'
		                    });
	                		update = 1;
	                		_this.findSuppliers();
	                		_this.loadOption();
	                		_this.showDialog = false
		                },
		                error: function (err) {
		                	if(err.status == 403){
                                errorMessage(_this.$message, "没有权限，请先申请该权限！");
                                return;
                            }
		                	if(err.responseJSON.message=="session clean"){
		                        errorMessage(_this.$message, '登陆已失效重新登陆!');
		                        toLogin();
		                        return;
		                    }
		                	_this.$alert('','保存失败', {
		                        confirmButtonText: '确定',
			                	type:'error',
			                	center:'true'
			            	});
		                }
		            });
		        	
				} else {
					return false
				}
			})
		},
		/*updateForm: function(formname) { //修改保存
			this.showDialog = false
			this.$set(this.suppliersList, this.selectedForm, this.suppliersForm)
			successMessage(this.$message, '修改成功')
		},*/
		createService: function() { //增加服务
			this.suppliersForm.suppliersServiceItems.push({
				suppliersServiceName: '',
				suppliersServicePrice: '',
				suppliersServiceContacts: this.suppliersForm.suppliersContacts,
				suppliersServicePhone: this.suppliersForm.suppliersPhone,
				suppliersServiceEmail: this.suppliersForm.suppliersEmail
			})
		},
		removeService: function(item) { //删除服务
			var index = this.suppliersForm.suppliersServiceItems.indexOf(item)
			if (index !== -1) {
				this.suppliersForm.suppliersServiceItems.splice(index, 1)
			}
		},
		/*
		 * 页面初始化,加载下拉选项
		 */
		loadOption : function() {
			var _this = this;
			$.ajax({
				url : '/suppliers/loadOption',
				type : 'get',
				dataType : 'json',
				success : function(res) {
					_this.suppliers = res.data.suppliers;// 供应商
					_this.suppliersServices = res.data.suppliersServices;// 服务项目
					_this.suppliersCategory = res.data.suppliersCategory;//供应商类别
				},
				error : function(err) {
					if(err.responseJSON.message=="session clean"){
                        errorMessage(_this.$message, '登陆已失效重新登陆!');
                        toLogin();
                        return;
                    }
					errorMessage(_this.$message, '初始化下拉列表出错！')
				}
			})
			 /**
	         * 获取用户机构及子机构
	         */
            $.ajax({
                url: '/getGlobalConstraints',
                type: 'get',
                dataType: 'json',
                success: function (res) {
                    _this.branchs = res.data.orgnsTree.orgnsChild
                    _this.branchs.push(res.data.orgnsTree)
                },
                error: function (err) {
                	if(err.responseJSON.message=="session clean"){
                        errorMessage(_this.$message, '登陆已失效重新登陆!');
                        toLogin();
                        return;
                    }
                    errorMessage(_this.$message, '查询数据字典出错！错误代码：'+(err.status))
                }
            })
		},
		/**
		 * 
		 * 处理页面数据展示
		 */
		exhibition : function(res) {
			var _this = this;
			_this.suppliersList = res.data.beanList
			var page = {}
			page['totalNumber'] = res.data.totalNumber
			page['totalPage'] = res.data.totalPage
			_this.pageBean = page
		},
		// 下载附件
		downloadFile : function(file) {
			window.location.href = '/suppliers/downloadFile?data='
					+ encodeURIComponent(JSON.stringify(file));
		},
		 /**
         * 下载查询数据
         */
        downloadsuppliers: function(){
        	var _this = this;
        	var data = "{}";
			if(_this.isSearch){
				data = JSON.stringify(_this.searchForm);
			}
        	window.location.href='/suppliers/downloadsuppliers?data='+encodeURIComponent(data);
        },
	}
})